const fs = require('fs');
const { objForEach } = require('../utils/objForEach');
const { PROTOCOL, PORT, IP } = require('../config');
const FILE_FOLDER = 'upload';
const catchAsync = require('../utils/catchAsync');
const AppError = require('../utils/appError.js');
/**
 * 获取随机数
 */
function getRandom() {
  return Math.random().toString(36).slice(-3);
}

/**
 * 给文件名加后缀，如 a.png 转换为 a-123123.png
 * @param {string} fileName 文件名
 */
function genRandomFileName(fileName = '') {
  // 如 fileName === 'a.123.png'

  const r = getRandom();
  if (!fileName) return r;

  const length = fileName.length; // 9
  const pointLastIndexOf = fileName.lastIndexOf('.'); // 5
  if (pointLastIndexOf < 0) return `${fileName}-${r}`;

  const fileNameWithOutExt = fileName.slice(0, pointLastIndexOf); // "a.123"
  const ext = fileName.slice(pointLastIndexOf + 1, length); // "png"
  return `${fileNameWithOutExt}-${r}.${ext}`;
}
exports.uploadimg = catchAsync((req, res) => {
  const imgLinks = [];
  // 遍历所有上传来的图片
  objForEach(req.files, (index, file) => {
    let oldName = file.filename; //获取名字
    let originalname = file.originalname; //originnalname其
    let newName1 = originalname;
    const newName = genRandomFileName(newName1); // 为文件名增加一个随机数，防止同名文件覆盖
    fs.renameSync('./public/upload/' + oldName, './public/upload/' + newName); //改图片的名字注意此处一定是一个路径，而不是只有文件名
    // 存储链接
    const url = `${PROTOCOL}://${IP}:${PORT}/${FILE_FOLDER}/${newName}`;
    imgLinks.push({ url, alt: newName, href: url });
  });
  let data;
  if (imgLinks.length === 1) {
    data = imgLinks[0];
  } else {
    data = imgLinks;
  }
  res.send({
    errno: 0, // 注意：值是数字，不能是字符串
    data: {
      data,
    },
  });
});

exports.uploadvideo = catchAsync((req, res) => {});
